package xworker.gluon.netty;

import io.netty.channel.ChannelHandlerContext;
import org.xmeta.ActionContext;
import xworker.gluon.netty.protocols.GluonMessages;
import xworker.netty.NettySession;
import xworker.netty.handlers.message.Handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GluonProoxyServer {
    private static final Map<String, Provider> providers = new HashMap<>();
    private static final Map<Long, Client> clients = new HashMap<>();

    @Handler(requestClass = GluonMessages.SendThingToClientReq.class)
    public static void handleSendThingToClientReq(GluonMessages.SendThingToClientReq req, NettySession session) throws IOException {
        GluonMessages.SendThingToClientResp.Builder resp = GluonMessages.SendThingToClientResp.newBuilder();

        Client client = clients.get(req.getClientId());
        if(client == null){
            resp.setResult(1);
        }else{
            GluonMessages.ClientReceiveThing.Builder msg = GluonMessages.ClientReceiveThing.newBuilder();
            msg.setPath(req.getPath());
            msg.setContent(req.getContent());

            client.sendMessage(msg.build());
            resp.setResult(0);
        }

        session.sendMessage(resp.build());
    }

    @Handler(requestClass = GluonMessages.ListClientsReq.class)
    public static void handleListClientsReq(GluonMessages.ListClientsReq req, NettySession session) throws IOException {
        GluonMessages.ListClientsResp.Builder builder = GluonMessages.ListClientsResp.newBuilder();
        Provider provider = Provider.getProvider(session);
        if(provider != null){
            List<Client> clientList = new ArrayList<>();
            for(Client client : provider.getClientList()){
                if(client.isClosed()){
                    clientList.add(client);
                }else {
                    GluonMessages.Client.Builder clientBuilder = GluonMessages.Client.newBuilder();
                    clientBuilder.setClientId(client.getId());
                    clientBuilder.setClientName(client.getName());
                    builder.addClientList(clientBuilder.build());
                }
            }

            for(Client client : clientList) {
                provider.removeClient(client);
            }
        }

        session.sendMessage(builder.build());
    }

    @Handler(requestClass = GluonMessages.ConnectProviderReq.class)
    public static void handleConnectProviderReq(GluonMessages.ConnectProviderReq req, NettySession session) throws IOException{
        Client client;
        synchronized (clients){
            client = Client.getClient(session);
            if(client == null){
                client = new Client();
                client.attach(session);
                clients.put(client.getId(), client);
            }
        }

        GluonMessages.ConnectProviderResp.Builder resp = GluonMessages.ConnectProviderResp.newBuilder();
        Provider provider = providers.get(req.getName());
        if(provider == null || !provider.getPassword().equals(req.getPassword())){
            resp.setResult(1);
        }else{
            resp.setResult(0);
            client.setName(req.getClientName());
            client.addProvider(provider);
        }

        session.sendMessage(resp.build());
    }

    /**
     * 内容提供者注册或连接到服务器。
     */
    @Handler(requestClass = GluonMessages.RegistProviderReq.class)
    public static void handleRegistProviderReq(GluonMessages.RegistProviderReq req, NettySession session) throws IOException {
        GluonMessages.RegistProviderResp.Builder resp = GluonMessages.RegistProviderResp.newBuilder();
        Provider provider = Provider.getProvider(session);
        if(provider != null){
            resp.setResult(2);
        }else {
            provider = providers.get(req.getName());
            if (provider == null) {
                provider = new Provider(req.getName(), req.getPassword());
                resp.setResult(0);
                providers.put(req.getName(), provider);
                provider.attach(session);
            } else if (!provider.getName().equals(req.getPassword())) {
                resp.setResult(1);
            } else {
                resp.setResult(0);
                provider.attach(session);
            }
        }
        session.sendMessage(resp.build());
    }

    public static void onWriterIdle(ActionContext actionContext){
        ChannelHandlerContext ctx = actionContext.getObject("ctx");
        ctx.channel().writeAndFlush(GluonMessages.HeartBeat.newBuilder().build());
    }

    public static void onSessionClosed(ActionContext actionContext){
        NettySession session = actionContext.getObject("session");
        Client client = Client.getClient(session);
        if(client != null){
            clients.remove(client.getId());
            client.onClosed();
        }
        Provider provider = Provider.getProvider(session);
        if(provider != null){
            provider.onProviderClosed();

            if(provider.getProviderCount() <= 0){
                providers.remove(provider.getName());
            }
        }
    }
}
